from fastapi import Depends, HTTPException, Header
from sqlalchemy import select, and_
from typing import Any, Optional

from ..basic.models import PERMISSION, User, Role, Permission, Repository, LogicalFile
from ..basic.database import get_db

# 固定的认证令牌
AUTH_TOKEN = "your-fixed-auth-token"

class AuthService:
    def __init__(self, 
                 db = Depends(get_db), 
                 authorization: str = Header(..., description="认证令牌")
                ):
        self.db = db
        self.token = authorization
        # print("authorization:", authorization)

    async def current(self) -> User:
        stmt = select(User).where(User.id == int(self.token))
        # 执行查询
        result = await self.db.execute(stmt)
        user = result.scalar_one_or_none()
        
        if user is None:
            raise HTTPException(
                status_code=400,
                detail=f"没有user: {self.token}"
            )
        return user

    async def validate(self, permission: PERMISSION, param: Optional[Any] = None) -> User:
        # 构建基础查询，一次性获取用户、权限和资源信息
        stmt = select(User, Permission).join(
            User.roles
        ).join(
            Role.permissions
        ).where(
            User.token == self.token,
            Permission.name == permission
        )

        # 根据权限类型和参数添加资源关联
        if param is not None:
            if permission in PERMISSION.repo():
                # 仓库相关权限，关联Repository表
                stmt = stmt.join(
                    Repository,
                    and_(
                        Repository.key == param,
                        Repository.owner_id == User.id
                    )
                )
            elif permission in PERMISSION.file():
                # 文件相关权限，关联LogicalFile和Repository表
                stmt = stmt.join(
                    LogicalFile,
                    and_(
                        LogicalFile.key == param,
                        LogicalFile.repository_id == Repository.id
                    )
                ).join(
                    Repository,
                    Repository.id == LogicalFile.repository_id
                )

        # 执行查询
        result = await self.db.execute(stmt)
        row = result.scalar_one_or_none()
        
        if row is None:
            raise HTTPException(
                status_code=403,
                detail=f"没有权限执行此操作: {permission}"
            )
            
        user, _ = row
        return user
